package jp.ac.nitech.matlab.najm.server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import jp.ac.nitech.matlab.najm.io.LiveTrace;
import jp.ac.nitech.matlab.najm.io.TraceFactory;
import jp.ac.nitech.matlab.najm.net.Packet;


/**
 * <[  بسم الله الرحمان الرحيم  ]
 * @author k-hon
 * SNodeHandler, handles the real data operations with clients
 * 		
 * Rules:
 * 	
 */

public class Handler implements Runnable {

	int ID;
	Socket socket; //got it from the master when the client connects
	MetaDataMap mdm; 
	LiveTrace trace = (LiveTrace)TraceFactory.getTrace();
	
	public Handler(int id, Socket sock) {
		this.ID = id;
		trace.info(this, ID, " new thread");
		socket = sock;
		mdm = MetaDataMap.getInstance();
	}
	
	public void run(){
		try {
			InputStream input = socket.getInputStream();
			OutputStream output = socket.getOutputStream();
			Packet p = new Packet(Packet.CTRL);
			input.read(p.getBuffer());
			String cmd = p.getCtrlCmd(); String target = p.getCtrlTarget();
			trace.info(this, ID, " ["+cmd+target+"] <= client");
			if(cmd.compareTo("FIN")==0) this.fin(); //exit .. send fin msg?
			//find file/SNode mapping
			String meta = mdm.findFile(target.trim()); //trim is temp
			//inform client of where the data is
			p = new Packet(Packet.CTRL);
			p.setControl("ADR", "0000", meta);
			if(meta==null) p.setControl("ERR", "0000", "not found");		
			output.write(p.getBuffer()); output.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//termination code
	private void fin()throws Exception{
		trace.info(this, ID, " Req.FIN <= client...\nClosing");
		this.socket.close();
	}
	
	//looks for file in cache
	private boolean inCache(String target){
		return false;
	}

}